<?php


namespace App\Http\Controllers\Api;


use App\Models\ImPersonalCertificate;
use App\Models\ImUsers;
use App\Services\Aliyun\Identify\IdCard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CertificationController
{
    /**
     * 申请个人实名认证
     * @param Request $req
     * @return \Illuminate\Http\JsonResponse
     */
    public function personal(Request $req)
    {
        $name = $req->post('name');
        $id_card_no = $req->post('id_card_no');
        $id_card_front = $req->post('id_card_front');
        $id_card_back = $req->post('id_card_back');
        $user_id = $req->user()['id'];
        if (empty($name) || empty($id_card_no) || empty($id_card_front) || empty($id_card_back)) {
            return errBack();
        }
        $count = ImPersonalCertificate::where('status', '<', 3)->where('user_id', $user_id)->count();
        if ($count) {
            return errBack('请勿重复认证');
        }
        $aliCheck = new IdCard();
        $checkRes = $aliCheck->checkNoName($id_card_no, $name);
        if (!$checkRes) {
            return errBack('认证失败，请稍后再试，或联系管理人员处理');
        }
        $user = ImUsers::find($user_id);
        DB::beginTransaction();
        try {
            $record = new ImPersonalCertificate();
            $record->name = $name;
            $record->user_id = $user_id;
            $record->status = 2;
            $record->id_card_no = $id_card_no;
            $record->id_card_front = $id_card_front;
            $record->id_card_back = $id_card_back;
            $record->third_party_result = $aliCheck->getMessage();
            $record->save();
            //更新用户认证状态
            $user->auth_status = 1;
            $user->save();
            DB::commit();
            return okBack();
        } catch (\Exception $e) {
            DB::rollBack();
            return errBack('申请出错，请联系客服');
        }
    }
}
